// @ts-ignore
import pub from "vc-subscribe-publish";
import router from "@/router";
import { NET_ERROR_TIPS } from "@/libs/useKeys";

export const useResponse = (res: any, resolve: (T: any) => void, reject: (T: any) => void) => {

  if (res.status === 401) {
    router.push({
      path: "/login"
    });
    reject(res.msg || res.message);
    try {
      res.json().then((result: any) => {
        pub.public(NET_ERROR_TIPS, result?.msg || result?.message || "modal.requestError");
      });
    } catch (e: unknown) {
      pub.public(NET_ERROR_TIPS || e || "modal.requestError");
    }
  } else if (res.status === 412) {
    router.push({
      path: "/unknown"
    });
    useResponseError(res, reject);
  } else if (res.status === 403) {
    router.push({
      path: "/403"
    });
    reject(res.message);
  } else if(res.status !== 200) {
      useResponseError(res, reject);
    } else {
      res
        .json()
        .then((result: any) => {
          if(result.code === 200){
            resolve(result)
          } else {
            useResponseError(result, reject);
          }
        })
        .catch(() => {

          reject(res.msg || res.message);
        });
      return;
    }

};

export const useResponseError = (res: any, reject?: any) => {
  if(res instanceof Object){
    pub.public(
      NET_ERROR_TIPS, res.msg || res.message || "modal.requestError"
    );
    reject(res);
    return
  }
  let message = "";
  try {
    res
      .json()
      .then((result: any) => {
        message = result?.msg || result?.messgae;
        pub.public(NET_ERROR_TIPS, message || "modal.requestError");
        reject(result)
      })
      .catch(function (e: Error & {msg: string}) {
        reject(e);
        pub.public(NET_ERROR_TIPS, e.message || e.msg || window.navigator.onLine ? "modal.requestError" : "modal.requestError");
      });
  } catch (e) {
    reject(e);
    pub.public(
      NET_ERROR_TIPS,
     res?.msg || res?.message || res?.statusText || res || window.navigator.onLine
        ? "modal.requestError"
        : "modal.requestError"
    );
  }

};
